package com.why.cachecloud.configuration;


import com.why.cachecloud.service.interceptor.AppAndInstanceAuthorityInterceptor;
import com.why.cachecloud.service.interceptor.FrontUserLoginInterceptor;
import com.why.cachecloud.service.interceptor.ManageUserLoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import java.util.*;

/**
 * spring-mvc.xml、spring-inspector.xml
 * spring-client-report.xml 修改为@Component形式注入
 */

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.why.cachecloud.client.heartbeat", "com.why.cachecloud.web.controller"})
public class WebConfig implements WebMvcConfigurer {

    @Resource
    FrontUserLoginInterceptor frontUserLoginInterceptor;
    @Resource
    AppAndInstanceAuthorityInterceptor appAndInstanceAuthorityInterceptor;
    @Resource
    ManageUserLoginInterceptor manageUserLoginInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/WEB-INF/resources/");

        registry.addResourceHandler("/assets/flash/**")
                .addResourceLocations("/WEB-INF/resources/assets/flash/");

        // 静态资源访问
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations("classpath:/static/", "classpath:/public/");
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(frontUserLoginInterceptor)
                .addPathPatterns("/admin/app/*", "/admin/instance/*", "/client/show/**", "/server/*");

        registry.addInterceptor(manageUserLoginInterceptor)
                .addPathPatterns("/manage/app/*", "/manage/instance/*", "/manage/user/*", "/manage/quartz/*",
                        "/manage/total/*", "/manage/machine/*", "/manage/notice/*", "/import/app/*",
                        "/manage/config/*", "/data/migrate/*", "/manage/redisConfig/*", "/manage/instanceAlert/*",
                        "/manage/redis/upgrade/*", "/manage/app/migrate/*");

        registry.addInterceptor(appAndInstanceAuthorityInterceptor)
                .addPathPatterns("/admin/app/*", "/admin/instance/*");
    }

    @Bean
    public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
        // 根据请求的URL扩展来响应不同的数据结构
        // 普通请求返回视图, .json请求返回JSON数据
        ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
        viewResolver.setOrder(1);
        viewResolver.setContentNegotiationManager(contentNegotiationManager());

        MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
        List<View> list = Collections.singletonList(mappingJackson2JsonView);

        viewResolver.setDefaultViews(list);
        return viewResolver;
    }

    private ContentNegotiationManager contentNegotiationManager() {
        Map<String, MediaType> mediaTypes = new HashMap<>();
        mediaTypes.put("json", MediaType.APPLICATION_JSON);

        PathExtensionContentNegotiationStrategy pathExtensionContentNegotiationStrategy = new PathExtensionContentNegotiationStrategy(mediaTypes);

        return new ContentNegotiationManager(pathExtensionContentNegotiationStrategy);
    }

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates/");
        configurer.setDefaultEncoding("UTF-8");
        configurer.setFreemarkerSettings(freemarkerSettings());
        return configurer;
    }

    private Properties freemarkerSettings() {
        Properties properties = new Properties();
        properties.setProperty("tag_syntax", "auto_detect");
        properties.setProperty("url_escaping_charset", "UTF-8");
        properties.setProperty("default_encoding", "UTF-8");
        properties.setProperty("output_encoding", "UTF-8");
        properties.setProperty("locale", "zh_CN");
        properties.setProperty("boolean_format", "true,false");
        properties.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
        properties.setProperty("date_format", "yyyy-MM-dd");
        properties.setProperty("time_format", "HH:mm:ss");
        properties.setProperty("number_format", "0.##");
        properties.setProperty("whitespace_stripping", "true");
        properties.setProperty("object_wrapper", "freemarker.ext.beans.BeansWrapper");
        return properties;
    }

    /**
     * 视图解析器,
     * @return
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        return new InternalResourceViewResolver("/WEB-INF/jsp/", ".jsp");
    }

}
